package com.wushijia.algorithm;

import java.util.Stack;

/**
 * 两个栈组成一个队列,将一个栈逆序成另一个栈后取出
 *
 * @author Administrator
 * @date 2021-06-10 15:00
 */
public class TwoStackQueue {

  private Stack<Integer> stackPush;
  private Stack<Integer> stackPop;

  public TwoStackQueue() {
    this.stackPush = new Stack<>();
    this.stackPop = new Stack<>();
  }

  private void pushToPop() {
    if (stackPop.empty()) {//只有当pop栈为空时，才能将push栈中数据一次全部放入
      while (!stackPush.empty()) {
        stackPop.push(stackPush.pop());
      }
    }
  }

  private void add(int newNum) {
    stackPush.push(newNum);
    pushToPop();
  }

  private int poll() {
    if (stackPush.empty() && stackPop.empty()) {
      throw new RuntimeException("pop stack is empty");
    }

    //先同步数据
    pushToPop();

    return stackPop.pop();
  }

  public int peek() {
    if (stackPush.empty() && stackPop.empty()) {
      throw new RuntimeException("stack is empty");
    }

    pushToPop();

    return stackPop.peek();
  }

}
